﻿using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.InventoryOrderDetail.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;

namespace DongFangGuoKai.WMSPlatform.Service.InventoryOrderDetail
{
    public class TInventoryOrderDetailService : ITInventoryOrderDetailService
    {
        private readonly SimpleRepositroy<TStocktakingOrderDetails> stocktakingOrderDetailsrepost;
        private readonly SimpleRepositroy<TStocktakingOrders> stocktakingOrdersrepost;
        private readonly SimpleRepositroy<TInventories> inventoriesrepost;
        private readonly SimpleRepositroy<TUsers> userrepost;

        public TInventoryOrderDetailService(SimpleRepositroy<TStocktakingOrderDetails> stocktakingOrderDetailsrepost)
        {
            this.stocktakingOrderDetailsrepost = stocktakingOrderDetailsrepost;

            stocktakingOrdersrepost = stocktakingOrderDetailsrepost.ChangeRepository<SimpleRepositroy<TStocktakingOrders>>();
            inventoriesrepost = stocktakingOrderDetailsrepost.ChangeRepository<SimpleRepositroy<TInventories>>();
            userrepost = stocktakingOrderDetailsrepost.ChangeRepository<SimpleRepositroy<TUsers>>();
        }


        /// <summary>
        /// pda上显示的数据
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<StocktakingOrdersDTO>? GetStocktakingOrderList(string? orderNo, int pageindex, int pagesize, out int totalCount)
        {
            totalCount = 0;
            var stkorderDetails = stocktakingOrderDetailsrepost.GetList(s => s.Status != 2);
            if (stkorderDetails.Count() <= 0)
            {
                return null;
            }
            totalCount = stkorderDetails.Count();
            if (!string.IsNullOrEmpty(orderNo))
            {
                stkorderDetails = stkorderDetails.Where(s=>s.OrderSn == orderNo).ToList();
            }
            stkorderDetails = stkorderDetails.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();

            List<StocktakingOrdersDTO> stocktakingOrders = new List<StocktakingOrdersDTO>();
            foreach (var stocktaking in stkorderDetails)
            {
                var data = stocktakingOrdersrepost.GetList(s => s.planId == stocktaking.OrderId);
                stocktakingOrders.Add(new StocktakingOrdersDTO
                {
                    stocktakingOrders = data,
                    Id = stocktaking.Id,
                    OrderId = stocktaking.OrderId,
                    CreateDate = stocktaking.CreateDate,
                    OrderSn = stocktaking.OrderSn,
                    Status = stocktaking.Status,
                    ExpectedStationIds = stocktaking.ExpectedStationIds,
                    checkedAll = false
                });
            }
            return stocktakingOrders;
        }

        /// <summary>
        ///修改盘点计划
        /// </summary>
        /// <param name="inventoryOrderNumberDTO"></param>
        /// <returns></returns>
        public bool UpdateStocktakingOrder(InventoryOrderNumberDTO inventoryOrderNumberDTO, out string message)
        {
            message = string.Empty;
            try
            {
                stocktakingOrderDetailsrepost.AsTenant().BeginTran();
                var robj = stocktakingOrderDetailsrepost.GetFirst(x => x.OrderSn == inventoryOrderNumberDTO.PlanNumber);
                if (robj == null)
                {
                    message = "未查询到盘点单";
                    return false;
                }
                if (robj.Status == 2)
                {
                    message = "盘点单已完成";
                    return false;
                }
                //盘点明细
                var stocktaking = stocktakingOrdersrepost.GetList(x => x.planId == robj.OrderId);
                if (stocktaking == null)
                {
                    message = "未查询到盘点明细！";
                    return false;
                }
                //提交人和监盘人
                var createUser = userrepost.GetFirst(u => u.Id == inventoryOrderNumberDTO.SupervisorId);
                if (createUser == null)
                {
                    message = "未查询到监盘人信息！";
                    stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                    return false;
                }
                var submitUser = userrepost.GetFirst(u => u.Id == inventoryOrderNumberDTO.UserId);
                if (submitUser == null)
                {
                    message = "未查询到提交人信息！";
                    stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                    return false;
                }
                foreach (var item in inventoryOrderNumberDTO.Items)
                {
                    var stocktakingOrder = stocktakingOrdersrepost.GetFirst(x => x.materialCode == item.MaterialCode && x.planId == inventoryOrderNumberDTO.PlanId && x.WarehouseName == item.StoreLocationCode);
                    if (stocktakingOrder == null)
                    {
                        message = "未查询到盘点单明细！";
                        stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                        return false;
                    }
                    
                    stocktakingOrder.qualityStatus = item.QualityStatus;
                    stocktakingOrder.FinishedCount = item.CheckAmount;
                    stocktakingOrder.MyProperty = item.CheckAmount - stocktakingOrder.CellCount;
                    if (stocktakingOrder.MyProperty == 0)
                    {
                        stocktakingOrder.Remark = "正常";
                    }
                    else if (stocktakingOrder.MyProperty > 0)
                    {
                        stocktakingOrder.Remark = "盘盈";
                    }
                    else if (stocktakingOrder.MyProperty < 0)
                    {
                        stocktakingOrder.Remark = "盘亏";
                    }
                    stocktakingOrder.Status = 4; //已完成

                    
                    stocktakingOrder.CreateUserId = createUser.Id;
                    stocktakingOrder.CreateUserName = createUser.UserName;

                    stocktakingOrder.SubmitUserId = submitUser.Id;
                    stocktakingOrder.SubmitUserName = submitUser.UserName;

                    if (!stocktakingOrdersrepost.Update(stocktakingOrder))
                    {
                        message = "修改盘点单明细失败！";
                        stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
            
                var stockStatus = stocktakingOrdersrepost.GetList(x => x.planId == robj.OrderId);
                if (stockStatus.Any(s => s.Status == 4))
                {
                    robj.Status = 2;
                    robj.ExpectedStationIds = "已盘点";
                }
                else
                {
                    robj.Status = 1;
                    robj.ExpectedStationIds = "未完成";
                }
                if (!stocktakingOrderDetailsrepost.Update(robj))
                {
                    message = "修改盘点单状态失败！";
                    stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                    return false;
                }
                message = "盘点完成!";
                stocktakingOrderDetailsrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                message = "盘点失败，" + ex.Message;
                stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                return false;
            }
        }

       
        /// <summary>
        /// 添加盘点单
        /// </summary>
        /// <param name="inventories"></param>
        /// <param name="planId"></param>
        /// <param name="planNumber"></param>
        /// <returns></returns>
        public bool AddStocktakingOrder(InventoryIssuanceModel inventoryIssuanceModel, out string message)
        {
            message = string.Empty;
            try
            {
                TStocktakingPlans jihua = new TStocktakingPlans();//盘点计划表
                if (inventoryIssuanceModel.Items == null || inventoryIssuanceModel.Items.Count == 0)
                {
                    message = "数据为空，或者格式不正确";
                    return false;
                }
                var stockOrder = stocktakingOrderDetailsrepost.GetFirst(x => x.OrderId == inventoryIssuanceModel.PlanId || x.OrderSn == inventoryIssuanceModel.PlanNumber);
                if (stockOrder != null)
                {
                    message = "盘点单已存在！";
                    return false;
                }
                stocktakingOrderDetailsrepost.AsTenant().BeginTran();
                TStocktakingOrderDetails stockingorder = new TStocktakingOrderDetails();//盘点单

                stockingorder.OrderId = inventoryIssuanceModel.PlanId;
                stockingorder.OrderSn = inventoryIssuanceModel.PlanNumber;
                stockingorder.Status = 0;
                stockingorder.ExpectedStationIds = "待盘点";
                stockingorder.CreateDate = DateTime.Now;
                stockingorder.Id = stocktakingOrderDetailsrepost.InsertReturnIdentity(stockingorder);
                if (stockingorder.Id <= 0)
                {
                    message = "盘点单添加失败！";
                    stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                    return false;
                }

                foreach (var item in inventoryIssuanceModel.Items)
                {
                    //查看库存是否有数据
                    var inventory = inventoriesrepost.GetFirst(x => x.LocationCode == item.StoreLocationCode && x.Status == 1);
                    if (inventory == null)
                    {
                        message = "未查询到库存数据";
                        stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                        return false;
                    }
                    TStocktakingOrders pandiandingid = new TStocktakingOrders();//盘点单明细
                    pandiandingid.BatchNo = item.Batch;//批次号
                    pandiandingid.MaterialName = item.MaterialName;//物资名称

                    pandiandingid.WarehouseId = item.StoreId;//库房id
                    pandiandingid.WarehouseCode = item.StoreName;//仓库名称
                                                              
                    pandiandingid.deptName = item.DeptName;//归属部门名称
                    pandiandingid.materialCode = item.MaterialCode;//物资编码
                    pandiandingid.materialNorms = item.MaterialNorms;//规格型号
                   
                    pandiandingid.PlanType = Convert.ToInt32(item.StoreLocationId);
                    
                    pandiandingid.WarehouseName = item.StoreLocationCode;//存放仓位
                    pandiandingid.storeLocationRemark = item.StoreLocationRemark;//存放仓位名称

                    pandiandingid.CellCount = item.StockCount; //库存数量
                    pandiandingid.PriorityLevel = stockingorder.Id;//关联的盘点计划我们的id
                    pandiandingid.LoopTimes = item.StockId; //物资系统库存明细id
                    pandiandingid.CreateDate = DateTime.Now;
                    pandiandingid.Status = 0;//创建
                    pandiandingid.planId = inventoryIssuanceModel.PlanId;//盘点计划id
                    pandiandingid.AuditUserName = inventoryIssuanceModel.PlanNumber;//盘点单号

                    if (!stocktakingOrdersrepost.Insert(pandiandingid))
                    {
                        message = "添加盘点单明细失败！";
                        stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
                stocktakingOrderDetailsrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                message = ex.Message;
                return false;
            }

        }

        /// <summary>
        /// 修改盘点单状态
        /// </summary>
        /// <param name="ordernum"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool UpdateStocktakingOrderStatus(string ordernum, out string message)
        {
            message = string.Empty;
            try
            {
                stocktakingOrderDetailsrepost.AsTenant().BeginTran();
                var robj = stocktakingOrderDetailsrepost.GetFirst(x => x.OrderSn == ordernum);
                if (robj == null)
                {
                    message = "未查询到盘点单！";
                    return false;
                }
                robj.Status = 2;
                robj.ExpectedStationIds = "已执行";
                if (!stocktakingOrderDetailsrepost.Update(robj))
                {
                    message = "修改盘点单失败！";
                    stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                    return false;
                }
                var uobj = stocktakingOrdersrepost.GetList(x => x.planId == robj.OrderId);
                if (uobj == null)
                {
                    message = "未查询盘点单明细！";
                    stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                    return false;
                }
                foreach (var item in uobj)
                {
                    item.Status = 2;
                    if (!stocktakingOrdersrepost.Update(item))
                    {
                        message = "修改盘点单明细失败！";
                        stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
                stocktakingOrderDetailsrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                message = "修改盘点单失败！" + ex.Message;
                stocktakingOrderDetailsrepost.AsTenant().RollbackTran();
                return false;
            }
        }

        /// <summary>
        /// pc盘点查询
        /// </summary>
        /// <param name="OrderNo"></param>
        /// <param name="status"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<StocktakingOrdersDTO>? GetStocktakingOrderListPC(string? orderNo, int? status, int pageindex, int pagesize, out int totalCount)
        {

            totalCount = 0;
            var stkorderDetails = stocktakingOrderDetailsrepost.GetList();
            if (stkorderDetails.Count() <= 0)
            {
                return null;
            }
            totalCount = stkorderDetails.Count();

            if (!string.IsNullOrEmpty(orderNo))
            {
                stkorderDetails = stkorderDetails.Where(s => s.OrderSn == orderNo).ToList();
            }
            if (status != null)
            {
                stkorderDetails = stkorderDetails.Where(s => s.Status == status).ToList();
            }
            stkorderDetails = stkorderDetails.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();

            List<StocktakingOrdersDTO> stocktakingOrders = new List<StocktakingOrdersDTO>();
            foreach (var stocktaking in stkorderDetails)
            {
                var data = stocktakingOrdersrepost.GetList(s => s.planId == stocktaking.OrderId);
                stocktakingOrders.Add(new StocktakingOrdersDTO
                {
                    stocktakingOrders = data,
                    Id = stocktaking.Id,
                    OrderId = stocktaking.OrderId,
                    CreateDate = stocktaking.CreateDate,
                    OrderSn = stocktaking.OrderSn,
                    Status = stocktaking.Status,
                    ExpectedStationIds = stocktaking.ExpectedStationIds,
                });
            }
            return stocktakingOrders;
        }
    }
}
